package com.hbwxz.admin.processor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCommonProcessor {

    @Autowired
    private RedisTemplate redisTemplate;

    public Object get(String key) {
        if(key == null){
            throw new UnsupportedOperationException("key should not be null");
        }
        return redisTemplate.opsForValue().get(key);
    }

    public void set(String key, Object value) {
        if(key == null){
            throw new UnsupportedOperationException("key should not be null");
        }
        redisTemplate.opsForValue().set(key, value);
    }

    public void set(String key, Object value, long timeout) {
        if(key == null){
            throw new UnsupportedOperationException("key should not be null");
        }
        if(timeout > 0){
            redisTemplate.opsForValue().set(key,value,timeout);
        }else{
            set(key,value);
        }
    }

    public void setExpiredDays(String key, Object value, int days) {
        if(key == null){
            throw new UnsupportedOperationException("key should not be null");
        }
        if(days > 0){
            redisTemplate.opsForValue().set(key,value,days, TimeUnit.DAYS);
        }else{
            set(key,value);
        }
    }

    public void remove(String key) {
        redisTemplate.delete(key);
    }

    public boolean getLock(String key,String uuid,long timeout,TimeUnit unit) {
        Boolean locked = redisTemplate.opsForValue().setIfAbsent(key, uuid, timeout, unit);
        return locked;
    }

    public Long runLuaScripts(String luaScript,String uuid,String key){
        DefaultRedisScript redisScript = new DefaultRedisScript(luaScript, Long.class);
        Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), uuid);
        return (Long)result;
    }

}
